//
//  BindingPhoneNumViewController.m
//  customer
//
//  Created by 杨阳 on 2018/10/29.
//  Copyright © 2018 yinlong. All rights reserved.
//

#import "BindingPhoneNumViewController.h"
#import "BindingPhoneNumTableViewCell.h"
#import "BindingPhoneCodeTableViewCell.h"
#import "SsehConfigModel.h"
#import "RSA.h"

@interface BindingPhoneNumViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView * tableView;

@property (nonatomic,strong) NSMutableArray * dataSource;

@end

static NSString * const BindingPhoneNumTableViewCellID = @"BindingPhoneNumTableViewCellID";

static NSString * const BindingPhoneCodeTableViewCellID = @"BindingPhoneCodeTableViewCellID";

@implementation BindingPhoneNumViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"绑定手机";
    [self layoutUI];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    BindingPhoneCodeTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    if (cell.labelTimer) {
        dispatch_suspend(cell.labelTimer);//退出界面时，读秒还在进行中，这时候应该暂停该队列
    }
}

-(void)layoutUI{
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(20, NAVIGATION_BAR_HEIGHT+70, F_DEVICE_W-40, 70+120+150) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.layer.cornerRadius = 5;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.backgroundColor = [UIColor backGroudColorForView];
    [self.tableView registerNib:[UINib nibWithNibName:@"BindingPhoneNumTableViewCell" bundle:nil] forCellReuseIdentifier:BindingPhoneNumTableViewCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"BindingPhoneCodeTableViewCell" bundle:nil] forCellReuseIdentifier:BindingPhoneCodeTableViewCellID];
    [self.view addSubview:self.tableView];
    
    UIView * footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W-40, 150)];
    footerView.backgroundColor = [UIColor backGroudColorForView];
    self.tableView.tableFooterView = footerView;
    
    UIButton * exitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    exitButton.titleLabel.font = [UIFont systemFontOfSize:16];
    exitButton.layer.cornerRadius = 5;
    [exitButton setTitle:@"绑定手机" forState:UIControlStateNormal];
    [exitButton setBackgroundColor:[UIColor blackColor]];
    [exitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [exitButton addTarget:self action:@selector(exitApp) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:exitButton];
    [exitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(footerView);
        make.height.mas_equalTo(50);
        
    }];
    
}

- (void)exitApp{
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:0];
    [dict setObject:[NSString emptyStr:self.infoManger.weixin_app_open_id]  forKey:@"weixin_app_open_id"];
    SsehConfigModel *configModel = self.dataSource.firstObject;
    SsehConfigModel *codeModel = self.dataSource.lastObject;
    [dict setObject:[NSString emptyStr:configModel.infoStr?:@""] forKey:@"member_account"];
    [dict setObject:codeModel.infoStr?:@"" forKey:@"code"];
    [dict setObject:self.infoManger.member_img forKey:@"member_img"];
    [dict setObject:self.infoManger.member_nick_name forKey:@"member_nick_name"];
    [self showLoading];
    [[QYNetManager sharedManager]POST:kWXAppBindMobile parameters:dict andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
        [self hideLoading];
        if (![responseObject[@"data"] isKindOfClass:[NSNull class]] && [responseObject[@"data"]isKindOfClass:[NSDictionary class]]) {
            [self showTipWithTitle:@"绑定成功"];
            //用户账号
            NSString * member_account = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"member_account"]];
            K_UserDefault_Write([NSString emptyStr:member_account], CustomerUserAccount);
            //用户id
            NSString * member_id = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"member_id"]];
            K_UserDefault_Write([NSString emptyStr:member_id], CustomerUserID);
            
            //token
            NSString * member_token = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"member_token"]];
            K_UserDefault_Write([NSString emptyStr:member_token], CustomerUserToken);
            
            //用户真实姓名
            K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"member_real_name"]], Customer_member_real_name);
            
            //用户手机号
            K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"member_phone"]], Customer_member_phone);
            
            //订单量
            K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"order_count"]], Customer_order_count);
            
            //用户头像
            K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"member_img"]], Customer_member_img);
            
            //微信openid
            K_UserDefault_Write([NSString emptyStr:self.infoManger.weixin_app_open_id], Customer_WXAppOpen_id);
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [self showErrorTipWithTitle:responseObject[@"error"]];
        }
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showErrorTipWithTitle:CustomerPoolNetStr];
    }];
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        BindingPhoneNumTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:BindingPhoneNumTableViewCellID];
        cell.backgroundColor = [UIColor backGroudColorForView];
        SsehConfigModel * model = self.dataSource[indexPath.row];
        [cell configData:model andIndex:indexPath];
        
        return cell;
    }else{
        BindingPhoneCodeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:BindingPhoneCodeTableViewCellID];
        cell.backgroundColor = [UIColor backGroudColorForView];
        SsehConfigModel * model = self.dataSource[indexPath.row];
        SsehConfigModel * phoneModel = [self.dataSource firstObject];
        [cell configData:model andPhoneModel:phoneModel];
        
        __weak typeof (self)weakSelf = self;
        cell.buttonClick = ^(UIButton *button) {
            [weakSelf verificateCode];
        };
        
        return cell;
    }
    
}

-(void)verificateCode{
    
    //kGetVerificateCode
    SsehConfigModel * model = [self.dataSource firstObject];
    
    [self showLoading];
    
    NSDictionary * par = @{@"mobile":[RSA encryptString:model.infoStr publicKey:CustomerRsaPublicKey],
                           @"code_type":[RSA encryptString:@"binding_mobile" publicKey:CustomerRsaPublicKey]};
    [[QYNetManager sharedManager]POST:kSendCode parameters:par andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
        [self hideLoading];
        //NSString * statusStr = [NSString stringWithFormat:@"%@",responseObject[@"status"]];
        
    } Failure:^(NSError *error) {
        [self hideLoading];
        [self showErrorTipWithTitle:error.localizedDescription];
    }];
    
}

-(NSMutableArray *)dataSource{
    
    if (_dataSource == nil) {
        
        _dataSource = [[NSMutableArray alloc]initWithCapacity:0];
        
        for (NSInteger i = 0; i < 2; i++) {
            SsehConfigModel * model = [[SsehConfigModel alloc]init];
            [_dataSource addObject:model];
            switch (i) {
                case 0:
                    model.placeHodleStr = @"手机号";
                    model.infoStr = @"";
                    break;
                case 1:
                    model.placeHodleStr = @"验证码";
                    model.infoStr = @"";
                    model.infoStr1 = @"获取验证码";
                    break;
                default:
                    break;
            }
            
        }
        
    }
    return _dataSource;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
